<?php
/*
 * @Author: lokei
 * @Date: 2022-09-15 23:26:06
 * @LastEditors: lokei
 * @LastEditTime: 2022-09-20 12:34:08
 * @Description: 
 */

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Redis;
use Tymon\JWTAuth\Facades\JWTAuth;

class ProjectMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $config = config()->all();
        $token = $request->header('Proj-Token');
        if(!is_null($token) && $token != '') {
            $payload = JWTAuth::setToken($token)->payload();
            $config['app']['proj_identity'] = $payload->get('pid');
            if(!is_null($payload->get('pid')) && ($payload->get('pid')) != '') {
                $config['database']['connections']['mysql']['database'] = $payload->get('pid') . '_' . env('DB_DATABASE', 'forge');
            } else {
                $config['database']['connections']['mysql']['database'] = env('DB_DATABASE', 'forge');
            }
        } else {
            $appid = $request->header('appid');
            if(Redis::exists('proj:endapp:' . $appid)) {
                $endapp = Redis::get('proj:endapp:' . $appid);
                $endapp_info = json_decode($endapp);
                $config['app']['proj_identity'] = $endapp_info->pid;
                $config['database']['connections']['mysql']['database'] = $endapp_info->pid . '_' . env('DB_DATABASE', 'forge');
            } else {
                $config['database']['connections']['mysql']['database'] = env('DB_DATABASE', 'forge');
            }
        }
        config($config);
        return $next($request);
    }
}
